"""
医院 CRUD 操作
"""
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from  crud.base import CRUDBase
from  models.hospital import Hospital
from  schemas.hospital import HospitalCreate, HospitalUpdate


class CRUDHospital(CRUDBase[Hospital, HospitalCreate, HospitalUpdate]):
    """医院CRUD操作"""
    
    async def get_by_name(self, db: AsyncSession, *, hospital_name: str) -> Optional[Hospital]:
        """
        根据医院名称获取医院
        
        Args:
            db: 数据库会话
            hospital_name: 医院名称
        
        Returns:
            医院对象或None
        """
        result = await db.execute(
            select(self.model).where(self.model.hospital_name == hospital_name)
        )
        return result.scalar_one_or_none()
    
    async def get_by_invite_code(self, db: AsyncSession, *, invite_code: str) -> Optional[Hospital]:
        """
        根据邀请码获取医院
        
        Args:
            db: 数据库会话
            invite_code: 邀请码
        
        Returns:
            医院对象或None
        """
        result = await db.execute(
            select(self.model).where(self.model.invite_code == invite_code)
        )
        return result.scalar_one_or_none()
    
    async def validate_code(
        self, 
        db: AsyncSession, 
        *, 
        hospital_name: str, 
        invite_code: str
    ) -> Optional[Hospital]:
        """
        验证医院名称和邀请码是否匹配
        
        Args:
            db: 数据库会话
            hospital_name: 医院名称
            invite_code: 邀请码
        
        Returns:
            医院对象或None
        """
        result = await db.execute(
            select(self.model)
            .where(self.model.hospital_name == hospital_name)
            .where(self.model.invite_code == invite_code)
            .where(self.model.status == 1)
        )
        return result.scalar_one_or_none()


# 创建全局实例
hospital = CRUDHospital(Hospital)

